//
//  Project_Step2ViewController.m
//  CMVRFForIOS
//
//  Created by zhangnorman on 15/4/11.
//  Copyright (c) 2015年 hvacapp. All rights reserved.
//

#import "Project_Step2ViewController.h"
#import "Project_Step3ViewController.h"
#import "Project_Step1ViewController.h"
#import "Project_Step5ViewController.h"
#import "Project_Step6ViewController.h"
#import "DefaultStyleTableViewCell.h"
#import "BottomActionView.h"
#import "Project_TabViewController.h"
#import "RoomInformationViewController.h"
#import "RoomData.h"
#import "ProjectManager.h"
#import "ProjectData.h"
#import <MBProgressHUD.h>
#import "RoomNameViewController.h"
#import "UITapView.h"
#import "SelectXSViewController.h"
#import "IndoorEquipDataResp.h"
#import "TwoLineWithDateCell.h"
#import "RoomInfoTableViewCell.h"
#import "ProjectContentViewController.h"

@interface Project_Step2ViewController () {
    MBProgressHUD *HUD;
}

@property (nonatomic,strong) UITableView *tableView;
@property (nonatomic,strong) BottomActionView *footerView;

@end

@implementation Project_Step2ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self setupViews];
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    [self.footerView updateCenterTitle:[[ProjectManager manager]getCurrentStepInfo]];
}

#pragma mark - 初始化视图
- (void)setupViews{
    self.title = @"房间信息";
    
    //自定义返回按钮
    UIBarButtonItem *backBtn = [[UIBarButtonItem alloc] initWithTitle:@"项目" style:UIBarButtonItemStyleDone target:self action:@selector(onBackToProject)];
    self.navigationItem.leftBarButtonItem = backBtn;
    
    //添加按钮
    UIBarButtonItem *addBtn = [[UIBarButtonItem alloc] initWithTitle:@"添加房间" style:UIBarButtonItemStyleDone target:self action:@selector(addNewRoom)];
    self.navigationItem.rightBarButtonItem = addBtn;
    
    //底部的上一步，下一步按钮
    self.footerView = [[BottomActionView alloc]initWithFrame:CGRectMake(0, self.view.height - KAction_Bar_Height - kNavigation_Bar_Height - kStatus_Bar_Height, kScreen_Width, KAction_Bar_Height)];
    if (iPhone_X) {
        self.footerView.y -= 34;
    }
    __block Project_Step2ViewController *tmp = (Project_Step2ViewController*)self;
    [self.footerView addLeftBtnBlock:^(id obj) {
        //需要跳过选择模板的步骤，所以返回到第一个页面
        //返回到第一个页面 调用2次，跳过2个页面，使得当期步骤是在1
        [[ProjectManager manager]goPage:1];
        for (UIViewController *item in tmp.navigationController.viewControllers) {
            if ([item isKindOfClass:[Project_Step1ViewController class]]) {
                [tmp.navigationController popToViewController:item animated:YES];
            }
        }
    }];
    [self.footerView addRightBtnBlock:^(id obj) {
//        for (RoomData *room in kProject.rooms) {
//            if (room.equips == nil || room.equips.count == 0) {
//                [Tools showMessageCenter:@"请先完善房间信息"];
//                return;
//            }
//        }
        [[ProjectManager manager]goNextPage];
        Project_Step3ViewController *view = [Project_Step3ViewController new];
        [tmp.navigationController pushViewController:view animated:YES];
    }];
    [self.footerView setLeftBtnTitle:@"上一步" andRightBtnTitle:@"下一步" andCenterTitle:[[ProjectManager manager] getCurrentStepInfo]];
    [self.view addSubview:self.footerView];
    
    //列表
    self.tableView = [[UITableView alloc] initWithFrame:[UIView frameWithOutNavBottom] style:UITableViewStylePlain];
    self.tableView.backgroundColor = UIColor16(0xeeeeee);
//    [self.tableView setTableFooterView:[[UIView alloc] initWithFrame:CGRectZero]];
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    [self.tableView setSeparatorColor: UIColor16(0xeeeeee)];
    
    [self.view addSubview:self.tableView];
}

/**
 *  直接跳转到项目页面
 */
-(void) onBackToProject{
    //返回到首页
    for (UIViewController *tmp in self.navigationController.viewControllers) {
        if ([tmp isKindOfClass:[Project_TabViewController class]]) {
            [(Project_TabViewController*)tmp refreshData];
            [self.navigationController popToViewController:tmp animated:YES];
        }
    }
}

/**
 *  添加新房间
 */
- (void)addNewRoom {
    RoomNameViewController *view = [RoomNameViewController new];
    view.userSelectedBlock = ^(RoomData *data) {
        [self addNewRoomData:data.room_name andType:data.room_type];
    };
    [self.navigationController pushViewController:view animated:YES];
}

#pragma 数据处理
- (void)addNewRoomData:(NSString*) room_name andType:(NSString*) room_type {
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    [params setValue:kProject.project_id forKey:@"project_id"];
    [params setValue:room_name forKey:@"room_name"];
    [params setValue:room_type forKey:@"room_type"];

    [HttpClient postWithUrl:HTTP_POST_PROJECT_ROOMS_ADD token:[AccountManager manager].token paramDic:params resultClass:[RoomData class] success:^(RoomData *obj) {
        if (kProject.rooms == nil) {
            kProject.rooms = [NSMutableArray new];
        }
        [kProject.rooms addObject:obj];
        [self.tableView reloadData];
    } failure:^(NSError *error) {
    }];
}

- (void)deleteRoomData:(NSInteger) tag {
    RoomData *date = [kProject.rooms objectAtIndex:tag];
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    [params setValue:date.project_room_id forKey:@"project_room_id"];
    [params setValue:kProject.project_id forKey:@"project_id"];
    [HttpClient getWithUrl:HTTP_GET_PROJECT_ROOMS_DELETE token:[AccountManager manager].token paramDic:params resultClass:[CommonResponse class] success:^(CommonResponse *obj) {
        [kProject.rooms removeObjectAtIndex:tag];
        [self.tableView reloadData];
    } failure:^(NSError *error) {
        [Tools showMessageCenter:@"删除房间失败！"];
    }];
}


#pragma mark - tableView显示设置数据
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return kProject.rooms.count;
}

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
    if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
        [cell setLayoutMargins:UIEdgeInsetsZero];
    }
    if ([cell respondsToSelector:@selector(setSeparatorInset:)]) {
        [cell setSeparatorInset:UIEdgeInsetsZero];
    }
}


-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *identifier = @"ProjectModuleCell";
    RoomInfoTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (cell == nil) {
        cell = [[RoomInfoTableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:identifier];
        
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    RoomData *item = [kProject.rooms objectAtIndex:indexPath.row];
    [cell setRoomData:item andDevices:item.equips];
    
    //滑动按钮
    cell.rightUtilityButtons = [self rightButtons];
    cell.delegate = self;
    cell.tag = indexPath.row;

    return cell;
}

-(NSArray *)rightButtons {
    NSMutableArray *rightUtilityButtons = [NSMutableArray new];
    [rightUtilityButtons sw_addUtilityButtonWithColor:[UIColor redColor] title:@"删除"];
    return rightUtilityButtons;
}


-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    RoomInformationViewController *view = [RoomInformationViewController new];
    view.currentIndex = indexPath.row;
    view.roomInfoChangedBlock = ^() {
        [self.tableView reloadData];
    };
    [self.navigationController pushViewController:view animated:YES];
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    RoomData *item = [kProject.rooms objectAtIndex:indexPath.row];
    BOOL hasDrpg = NO;
    if ([item.terminal_type containsString:@"地暖"] && item.pipe_length > 0) {
        hasDrpg = YES;
    }
    NSInteger count = item.equips == nil ? 0 : item.equips.count;
    return [RoomInfoTableViewCell cellHeight:count hasDrpg:hasDrpg];
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    return [[UIView alloc]initWithFrame:CGRectMake(0, 0, kScreen_Width, DEFAULT_SECTION_HEIGHT)];
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return DEFAULT_SECTION_HEIGHT;
}
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    return [[UIView alloc]initWithFrame:CGRectMake(0, 0, kScreen_Width, CGFLOAT_MIN)];
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return CGFLOAT_MIN;
}


#pragma mark - 滑动按钮代理协议
/**
 *  右侧滑动按钮点击事件
 *
 *  @param cell  单元cell
 *  @param index 下标
 */
-(void)swipeableTableViewCell:(SWTableViewCell *)cell didTriggerRightUtilityButtonWithIndex:(NSInteger)index{
    switch (index) {
        case 0:{
            [self deleteRoomData:cell.tag];
            break;
        }
            
        default:
            break;
    }
    [cell hideUtilityButtonsAnimated:YES];
}


/**
 *  滑动的时候把其他的隐藏掉
 *
 *  @param cell cell
 *
 *  @return 隐藏其他的cell
 */
-(BOOL)swipeableTableViewCellShouldHideUtilityButtonsOnSwipe:(SWTableViewCell *)cell{
    return YES;
}





- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
